package com.borrow.jiemihua.mainUI.fragment;


import android.Manifest;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.borrow.jiemihua.R;
import com.borrow.jiemihua.base.BaseConstant;
import com.borrow.jiemihua.base.BaseFragment;
import com.borrow.jiemihua.base.URLConstant;
import com.borrow.jiemihua.dialog.iosdialog.ShareDialog;
import com.borrow.jiemihua.mainUI.activity.FeedbackActivity;
import com.borrow.jiemihua.mainUI.activity.MyGoldActivity;
import com.borrow.jiemihua.mainUI.activity.MyMessageActivity;
import com.borrow.jiemihua.mainUI.activity.QuestionActivity;
import com.borrow.jiemihua.mainUI.activity.SettingActivity;
import com.borrow.jiemihua.utils.PermissionUtils;
import com.borrow.jiemihua.utils.SharedPreferencesUtils;
import com.borrow.jiemihua.utils.xutils3.MyCallBack;
import com.borrow.jiemihua.utils.xutils3.XUtil;
import com.pure.share.ShareHelper;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import cc.duduhuo.custoast.CusToast;


/**
 * A simple {@link Fragment} subclass.
 */
public class PersonFragment extends BaseFragment implements View.OnClickListener {
    private View view;
    private TextView tv_qiandao;
    private TextView tv_jifen;
    private TextView tv_phone;
    private int isQD;
    PermissionUtils mPermissionUtils;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public View initView(LayoutInflater inflater) {
        view = inflater.inflate(R.layout.fragment_person, null);
        initData();
        initViews();
        upQDZTData();
        return view;
    }

    @Override
    public void initData() {
        mPermissionUtils = new PermissionUtils(getActivity(), new PermissionUtils.Listener() {
            @Override
            public void onPermissionSucceed(String permission) {
                onPermissionGranted(permission);
            }
        });
    }

    private void initViews() {
        tv_jifen = (TextView) view.findViewById(R.id.tv_jifen);
        tv_qiandao = (TextView) view.findViewById(R.id.tv_qiandao);
        tv_phone = (TextView) view.findViewById(R.id.tv_phone);
        tv_qiandao.setOnClickListener(this);
        view.findViewById(R.id.rl_yaoqing).setOnClickListener(this);
        view.findViewById(R.id.rl_Message).setOnClickListener(this);
        view.findViewById(R.id.rl_opinion).setOnClickListener(this);
        view.findViewById(R.id.rl_question).setOnClickListener(this);
        view.findViewById(R.id.rl_setting).setOnClickListener(this);
        view.findViewById(R.id.rl_my_jf).setOnClickListener(this);
        view.findViewById(R.id.rl_setting).setOnClickListener(this);
        view.findViewById(R.id.ll_me).setOnClickListener(this);
        String phone = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.MOBILEPHONE, "");
        if (!phone.equals("")) {
            if (phone.length() > 9) {
                StringBuilder builder = new StringBuilder(phone);
                builder.replace(3, 7, "****");
                tv_phone.setText(builder.toString());
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_me:
//                jumpActivity(PersonalDataActivity.class,null);
                break;
            case R.id.rl_my_jf:
                jumpActivity(MyGoldActivity.class, null);
                break;
            case R.id.tv_qiandao:
                if (isQD == 0) {
                    upQDData();
                } else {
                    return;
                }

                break;
            //邀请好友
            case R.id.rl_yaoqing:
//                jumpActivity(InvitePrizeActivity.class,null);
//                mPermissionUtils.onPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
                upYQData();
                break;
            case R.id.rl_Message:
                jumpActivity(MyMessageActivity.class, null);
                break;
            case R.id.rl_opinion:
                jumpActivity(FeedbackActivity.class, null);
                break;
            case R.id.rl_question:
                jumpActivity(QuestionActivity.class, null);
                break;
            case R.id.rl_setting:
                jumpActivity(SettingActivity.class, null);
                break;
        }
    }

    private String content;
    private String linkUrl;
    private String title;

    private void upYQData() {
        Map<String, String> map = new HashMap<>();
        String userid = SharedPreferencesUtils.getString(getContext(), BaseConstant.SPConstant.USERID, "");
        map.put("userId", userid);
        map.put("packet", "Android");
        showDialog();
        XUtil.Get(URLConstant.YAOQINGHAOYOU, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==查看邀请码", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.optString("isSuccess").equals("1")) {
                        String data = jsonObject.optString("data");
                        JSONObject Object = new JSONObject(data);
                        content = Object.optString("content");
                        linkUrl = URLConstant.URL + Object.optString("linkUrl");
                        title = Object.optString("title");
                        share();
                    } else {
                        CusToast.showToast("分享错误");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
                closeDialog();
            }
        });
    }

    ShareDialog mShareDialog;
    SHARE_MEDIA mShareMedia;

    private void share() {
        if (mShareDialog == null) {
            mShareDialog = new ShareDialog(getContext(), new ShareDialog.ClickLinstener() {
                @Override
                public void onShare(SHARE_MEDIA shareMedia) {
                    mShareMedia = shareMedia;
                    mPermissionUtils.onPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
                }
            });
        }
        mShareDialog.show();
//        ShareHelper.getInstance(getActivity()).share(getActivity(), title, null, linkUrl);
    }

    /**
     * 授权成功
     *
     * @param permission
     */
    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                ShareHelper.getInstance(getActivity()).share(mShareMedia, "贷钱么", "我在“贷钱么”上借款，放款速度超快...", null, linkUrl);
                if (mShareDialog != null) {
                    mShareDialog.dismissDialog();
                }
                break;
        }
    }

    /**
     * 得到Bitmap的byte
     *
     * @param bmp 图片
     * @return 返回压缩的图片
     */
    private static byte[] bmpToByteArray(Bitmap bmp) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private void upXQJFData() {
        Map<String, String> map = new HashMap<>();
        String userid = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.USERID, "");
        map.put("userId", userid);
        showDialog();
        XUtil.Get(URLConstant.CHAXUNJIFEN, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==查询积分", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.optString("isSuccess").equals("1")) {
                        String data = jsonObject.optString("data");
                        tv_jifen.setText(data);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
                closeDialog();
            }
        });
    }

    private void upQDData() {
        Map<String, String> map = new HashMap<>();
        String userid = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.USERID, "");
        map.put("userId", userid);
        showDialog();
        XUtil.Get(URLConstant.MY_QIAODAO, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==签到", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    if (res.equals("1")) {
                        tv_qiandao.setText("已签到");
                        isQD = 1;
                        tv_qiandao.setBackgroundResource(R.drawable.myqiandao_button_wu);
                        CusToast.showToast("签到成功");
                        upXQJFData();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });
    }

    private void upQDZTData() {
        Map<String, String> map = new HashMap<>();
        String userid = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.USERID, "");
        map.put("userId", userid);
        map.put("activityId", "3");
        map.put("unitCode", "1");
//        showDialog();
        XUtil.Get(URLConstant.QIANDAOIS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==是否签到", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    String data = jsonObject.optString("data");
                    if (res.equals("1")) {
                        if (data.equals("0")) {
                            isQD = 0;
                            tv_qiandao.setBackgroundResource(R.drawable.myqiandao_button);
                            tv_qiandao.setText("签到");
                        } else {
                            isQD = 1;
                            tv_qiandao.setText("已签到");
                            tv_qiandao.setBackgroundResource(R.drawable.myqiandao_button_wu);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        upXQJFData();
        upQDZTData();
    }
}
